package com.twan.kotlinbase.viewstubpresenter

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewStub
import android.widget.*
import butterknife.ButterKnife
import butterknife.OnClick
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.lxj.xpopup.XPopup
import com.skydoves.powerspinner.PowerSpinnerView
import com.twan.kotlinbase.R
import com.twan.kotlinbase.app.BaseDataBindingFragment
import com.twan.kotlinbase.app.Need
import com.twan.kotlinbase.bean.Dict
import com.twan.kotlinbase.bean.GuigeZuhe
import com.twan.kotlinbase.bean.ModelActor
import com.twan.kotlinbase.bean.UploadPic
import com.twan.kotlinbase.databinding.Viewstub1VideoExtBinding
import com.twan.kotlinbase.databinding.Viewstub2ShotBinding
import com.twan.kotlinbase.event.TakePhotoEvent
import com.twan.kotlinbase.event.TichengEvent
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.pop.AddPicPopup
import com.twan.kotlinbase.ui.GuigeActivity
import com.twan.kotlinbase.ui.SendActivity
import com.twan.kotlinbase.ui.TichengRateActivity
import com.twan.kotlinbase.util.*
import com.twan.kotlinbase.widgets.router.Router
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import kotlinx.android.synthetic.main.viewstub2_shot.*
import kotlinx.android.synthetic.main.viewstub2_shot.btn_ok
import kotlinx.android.synthetic.main.viewstub2_shot.chb_privacy
import kotlinx.android.synthetic.main.viewstub2_shot.rv_multi_pic
import kotlinx.android.synthetic.main.viewstub2_shot.rv_multi_video
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

//1-需求,2-服务
//发需求:拍摄
class Shot2Presenter: BaseDataBindingFragment<Viewstub2ShotBinding>() {
    var cacheServiceId=""
    override fun getLayoutId(): Int {
        return R.layout.viewstub2_shot
    }
    lateinit var currImageView:ImageView
    var modelActorList= mutableListOf<ModelActor>()
    override fun initView(view: View?, savedInstanceState: Bundle?) {
        //添加演员模特
        tv_add.setOnClickListener { addModelActor() }
        initRvMultiPicOrVideo(rv_multi_pic,1)
        initRvMultiPicOrVideo(rv_multi_video,2)
        initRvMultiPicOrVideo(rv_multi_anli,4)


        btn_ok.setOnClickListener {
            if (uploadPics.size==1 && uploadVideos.size==1) {
                ToastUtils.showShort("请上传主图,二选一")
                return@setOnClickListener
            }
            if (!InputUtils.checkEmpty(edt_shot_spec,edt_team_cnt,edt_good_type)){
                return@setOnClickListener
            }
            if (uploadAnlis.size==1) {
                ToastUtils.showShort("请上传案例图片")
                return@setOnClickListener
            }
            if (!chb_privacy.isChecked){
                ToastUtils.showShort("请勾选交易规则")
                return@setOnClickListener
            }
            //检查新增的平台的url是否有空
            if (!checkUrls()){
                ToastUtils.showShort("请上传新增模特演员的图片或视频")
                return@setOnClickListener
            }


            RxHttpScope().launch {
                //规格组合列表
//                var guigeZuheList=RxHttp.get("serviceSku/findAllByServiceId").add("serviceId",cacheServiceId).toResponse<List<GuigeZuhe>>().await()
//                if (guigeZuheList.isNullOrEmpty()){
//                    ToastUtils.showShort("请将规格填写完整")
//                    return@launch
//                }

                var req=RxHttp.get("service/shortVideoMake/createId").toResponse<String>().await()
                cacheServiceId=req

                RxHttp.postJson("service/shortVideoMake/save")
                    .add("caseUrl", getAnliUrl())
                    .add("id", cacheServiceId)
                    .add("imageUrl", getPicsUrl())
                    .add("price", "")//每条价格
                    .add("recommendFlag", "0")
                    .add("recommendTime", "")
                    .add("score", "5")//0
                    .add("serviceTypeLabel", Need.SHORT_VIDEO_MAKE.title)
                    .add("serviceTypeValue", Need.SHORT_VIDEO_MAKE.desc)
                    .add("shootSpecialtyLabel", edt_shot_spec.text.toString())//拍摄特长
                    .add("siteTypeLabel", if (rb_local.isChecked) rb_local.text.toString() else rb_out.text.toString())
                    .add("siteTypeValue", if (rb_local.isChecked) "1" else "2")// 场地类型
                    .add("specialtyTypeLabel", edt_good_type.text.toString())//擅长类型
                    .add("teamNum", edt_team_cnt.text.toString())
                    .add("title", "发布短视频制作服务-"+DateUtils.today2())
                    .add("userId", MyUtils.getLoginInfo()!!.userId)
                    .add("videoUrl", getVideosUrl())
                    .add("modelActorList", modelActorList)
                    .toResponse<Any>().await()
                ToastUtils.showShort("发布短视频拍摄成功")
                mActivity.finish()
            }
        }
    }

    //规格
    @OnClick(R.id.spi_guige)
    fun guige(){
        RxHttpScope().launch {
            if (cacheServiceId.isEmpty()){
                var req=RxHttp.get("service/shortVideoMake/createId").toResponse<String>().await()
                cacheServiceId=req
                Router.newIntent(mActivity).putString("serviceId",cacheServiceId).to(GuigeActivity::class.java).launch()
            } else {
                Router.newIntent(mActivity).putString("serviceId",cacheServiceId).to(GuigeActivity::class.java).launch()
            }
        }
    }


    //图片选择结果处理
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }

    //主图只能选择其一
    override fun uploadCallback(url:String){
        if (uploadType == 1){ //选择了图片就清空视频
            //clear(2)
            //rv_multi_video.adapter!!.notifyDataSetChanged()

            uploadPics.add(UploadPic(filepath=url))
            rv_multi_pic.adapter!!.notifyDataSetChanged()
        } else if (uploadType ==2){ //选择了视频就清空图片
            //clear(1)
            //rv_multi_pic.adapter!!.notifyDataSetChanged()

            uploadVideos.add(UploadPic(filepath=url))
            rv_multi_video.adapter!!.notifyDataSetChanged()
        } else if (uploadType ==4) {
            uploadAnlis.add(UploadPic(filepath=url))
            rv_multi_anli.adapter!!.notifyDataSetChanged()
        } else { //单个的图片或者视频
            if (::currImageView.isInitialized){
                currImageView.tag=url
                GlideUtils.load(mActivity,currImageView,url)
            }
        }
    }

    var viewList= mutableListOf<View>()
    fun addModelActor(){
        var view = layoutInflater.inflate(R.layout.add_video_shot,ll_container,false)
        var iv_del = view.findViewById<ImageView>(R.id.iv_del)
        var tv_name = view.findViewById<TextView>(R.id.tv_name)
        var upload_pic2 = view.findViewById<ImageView>(R.id.upload_pic1)
        var upload_video2 = view.findViewById<ImageView>(R.id.upload_video1)
        viewList.add(view)
        tv_name.text="模特/演员${viewList.size}"
        ll_container.addView(view)
        iv_del.setOnClickListener {
            viewList.remove(view)
            ll_container.removeView(view)
            updateName()
        }
        upload_pic2.setOnClickListener {
            currImageView=upload_pic2
            uploadType=3
            XPopup.Builder(mActivity).asCustom(AddPicPopup(mActivity,mFragment)).show()
        }
        upload_video2.setOnClickListener {
            currImageView=upload_video2
            uploadType=3
            XPopup.Builder(mActivity).asCustom(AddPicPopup(mActivity,mFragment,mimeType = MimeType.ofVideo())).show()
        }

    }

    fun updateName(){
        viewList.forEachIndexed { index, view ->
            var tv_name = view.findViewById<TextView>(R.id.tv_name)
            tv_name.text="模特/演员${index+1}"
        }
    }
    //获取新增平台的图片,视频的url
    fun checkUrls():Boolean{
        modelActorList.clear()
        viewList.forEach {
            var tv_name = it.findViewById<TextView>(R.id.tv_name)
            var upload_pic2 = it.findViewById<ImageView>(R.id.upload_pic1)
            var upload_video2 = it.findViewById<ImageView>(R.id.upload_video1)
            if (upload_pic2.tag==null || upload_video2.tag==null){
                return false
            }
            modelActorList.add(ModelActor("",tv_name.text.toString(),upload_pic2.tag as String,upload_video2.tag as String,"",tv_name.text.toString()))
        }
        return true
    }

}